<?php 
class AsteriskManager {

  var $socket;
  var $error;
  
  // Constructor
  function AsteriskManager()
  {
    $this->socket = FALSE;
    $this->error = "";
  }

    // Login
  function Login($host="localhost", $username="admin", $password="amp111"){
    $this->socket = @fsockopen($host,"5038", $errno, $errstr, 1); 
    if (!$this->socket) {
      $this->error =  "Could not connect - $errstr ($errno)";
      return FALSE;
    }else{
      stream_set_timeout($this->socket, 1); 
      $wrets = $this->SendCommand("Action: Login\r\nUsername: $username\r\nSecret: $password\r\nEvents: off\r\n\r\n");

     	if (strpos($wrets, "Message: Authentication accepted") != FALSE){
        return true;
      }else{
  		  $this->error = "Could not login - Authentication failed";
        fclose($this->socket); 
        $this->socket = FALSE;
  		  return FALSE;
   	  }
    }
  }
    // Logout
  function Logout(){
      $wrets = "";

    if ($this->socket){
      fputs($this->socket, "Action: Logoff\r\n\r\n"); 
      while (!feof($this->socket)) { 
        $wrets .= fread($this->socket, 8192); 
      } 
      fclose($this->socket); 
      $this->socket = "FALSE";
    }
  	return; 
  }

    // Send command to AMI
  function SendCommand($cmd){
    $wrets = "";
    
    if ($this->socket === FALSE)
      return FALSE;
      
    fputs($this->socket, $cmd);
    do
    {
      $line = fgets($this->socket, 4096);
      $wrets .= $line;
      $info = stream_get_meta_data($this->socket);
    }while ($line != "\r\n" && $info['timed_out'] == false );
    return $wrets;
  }

    // Get last error
  function GetError(){
    return $this->error;
  }
  
  
}
?> 